import R from '@/common/type/response';
import { NextApiResponse } from 'next';
import * as roleMenuService from '@/common/service/sys_role_menu';
import { AuthenticatedRequest, withAuth } from '@/common/middleware/auth';

export async function handler(req: AuthenticatedRequest, res: NextApiResponse) {
  try {
    const { role_id } = req.query;
    
    if (!role_id) {
      return R.error(res, '缺少角色ID');
    }

    if (req.method === 'GET') {
      // 获取角色的菜单列表
      const menus = await roleMenuService.getRoleMenus(Number(role_id));
      R.success(res, menus);
    } else if (req.method === 'POST') {
      // 更新角色的菜单
      const { menu_ids } = req.body;
      if (!Array.isArray(menu_ids)) {
        return R.error(res, '菜单ID必须是数组');
      }
      
      await roleMenuService.updateRoleMenus(Number(role_id), menu_ids);
      R.success(res);
    } else {
      res.status(405).json({ success: false, message: 'Method Not Allowed' });
    }
  } catch (e: any) {
    R.error(res, e.message);
  }
}

export default withAuth(handler); 